Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

213
Visualizações
"JavaScript - The Definitive Guide" - "The call() and apply() Methods"

I've tried out this code and it doesn't work:

function benchmark(n) {
  let sum = 0;
  for(let i = 1; i <= n; i++) sum += i;
  return sum;
}

function trace(o, m) {
  let original = o[m];
  o[m] = function(...args) {
    console.log(new Date(), "Entering:", m);
    let result = original.apply(this, args);
    console.log(new Date(), "Exiting:", m);
    return result;
  };
}

obj = {};
benchmark.call(obj);
trace(obj, "benchmark");
obj.benchmark(1000000);
obj["benchmark"](1000000);

The error is Uncaught TypeError: Cannot read properties of undefined (reading 'apply') at Object.o.<computed> [as benchmark]. This error happens at let result = original.apply(this, args); because it was indicated by the error line number in the Console.

This error is not resolved if I use apply() in benchmark.call(obj):

benchmark.apply(obj);

This error is only resolved if I use this:

obj.benchmark = benchmark;

I extract this from "JavaScript - The Definitive Guide":

call() and apply() allow you to indirectly invoke a function as if it were a method of some other object. The first argument to both call() and apply() is the object on which the function is to be invoked; this argument is the invocation context and becomes the value of the this keyword within the body of the function. To invoke the function f() as a method of the object o (passing no arguments), you could use either call() or apply():

f.call(o);
f.apply(o);

So, why wouldn't benchmark.call(obj); or benchmark.apply(obj); work in my code?

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda